package com.weavernorth.retailExperienceAward;

import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;
import com.weavernorth.retailExperienceAward.dto.sapMessEntity;
import com.weavernorth.retailExperienceAward.utils.sendDataToSapUtils;
import com.weavernorth.util.Logger4jUtil;
import com.weavernorth.util.dateUtils;
import org.apache.log4j.Logger;
import weaver.conn.ConnectionPool;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class qyjlAmountTotalToSAPTimmer extends BaseCronJob {
    //    private Logger log = Logger4jUtil.getLoggerByName("/Timmer/qyjlAmountTotalToSAPTimmer/");
    public String cycle;

    public String getcycle() {
        return cycle;
    }

    public void setcycle(String cycle) {
        this.cycle = cycle;
    }

    public static ConnectionPool pool = ConnectionPool.getInstance();
    public Connection conn;
    public Statement statement;

    @Override
    public void execute() {
        Logger log = Logger4jUtil.getLoggerByName("/Timmer/qyjlAmountTotalToSAPTimmer/");
        RecordSet rs_kk = new RecordSet();
        RecordSet rs = new RecordSet();
        RecordSet rsUpdate = new RecordSet();
        log.info("区域经理零售体验奖传SAP数据开始。。。");
        String strKhzq = dateUtils.previousMonth(0);//0:当前年月所对应的周期
        if (cycle != null) {
            strKhzq = dateUtils.previousMonth(Integer.parseInt(cycle));
        }
        log.info("考核周期为：" + strKhzq);
        Boolean isNext = true;//是否进行下一步操作
        try {
            conn = pool.getConnection();
            statement = conn.createStatement();
            //uf_cwkkbb:不取BE和童装的数据 即ywdy not in(3,4)
            String strQuery_kk = "SELECT a.khzq,a.yggh,a.sfqbkc,a.csjlsftykh,a.kkje,a.sfyqs,b.jjje FROM uf_cwkkbb a,uf_zddpgrjj_qyjl b WHERE a.ywdy not in(3,4)  AND (a.sfyqs is NULL OR  a.sfyqs=0) and a.khzq=b.khzq AND a.yggh=b.gh and a.khzq='" + strKhzq + "'";
            log.info("零售体验奖及财务扣款联合查询：" + strQuery_kk);
            rs_kk.execute(strQuery_kk);
            String yggh = "";//员工工号
            String sfqbkc = "";//是否全部扣除(0:是,1：否)
            String csjlsftykh = "";//	城市经理是否同意考核(0:是,1：否)
            String kkje = "";//扣款金额
            String jjje = "";//奖金金额
            String zzje = "";//最终金额
            String kkqje = "";//财务扣款前金额
            Integer temp;
            while (rs_kk.next()) {
                yggh = Util.null2String(rs_kk.getString("yggh"));
                sfqbkc = Util.null2String(rs_kk.getString("sfqbkc"));
                csjlsftykh = Util.null2String(rs_kk.getString("csjlsftykh"));
                jjje = Util.null2s(rs_kk.getString("jjje"), "0.00");
                kkqje = jjje;
                BigDecimal b_jjje = new BigDecimal(jjje);
                if ("0".equals(csjlsftykh)) {
                    //城市经理同意考核时,参与财务奖金扣除逻辑
                    if ("0".equals(sfqbkc)) {
                        //全部扣除时，奖金为0
                        zzje = "0.00";
                        kkje = jjje;
                    } else {
                        kkje = Util.null2s(rs_kk.getString("kkje"), "0.00");
                        BigDecimal b_kkje = new BigDecimal(kkje);
                        temp = b_kkje.compareTo(b_jjje);
                        if (temp == 0) {
                            zzje = kkje;
                        } else if (temp > 0) {
                            zzje = "0.00";
                        } else {
                            zzje = b_jjje.subtract(b_kkje).toString();
                        }
                    }
                    String updateSql = "update uf_zddpgrjj_qyjl set cwkkqjjje='" + kkqje + "',jjje='" + zzje + "',cwkkje='" + kkje + "' where khzq='" + strKhzq + "' and gh='" + yggh + "'";
                    statement.addBatch(updateSql);
                    //uf_cwkkbb表更新是否已取数字段
                    String updateBack = "update uf_cwkkbb set sfyqs='1' where khzq='" + strKhzq + "' and yggh='" + yggh + "'";
                    statement.addBatch(updateBack);
                    log.info("财务扣款后数据：员工编号：" + yggh + ",是否全部扣除：" + sfqbkc + ",城市经理是否同意考核：" + csjlsftykh + ",奖金金额：" + jjje + ",财务扣款：" + kkje + ",最终奖金：" + zzje);
                }
            }
            Long begin1 = System.currentTimeMillis();
            statement.executeBatch();
            Long end1 = System.currentTimeMillis();
            log.info("批量更新耗时：" + (end1 - begin1) + "(毫秒)");
            conn.close();
            statement.close();
        } catch (Exception ex) {
            isNext = false;
            log.info("批处理异常,异常信息：" + ex.toString());
        }
        if (isNext) {
            String strQueryAll = "select * from uf_zddpgrjj_qyjl where khzq='" + strKhzq + "' and (tsjg is null or tsjg=1) AND fwbz40 is not null AND clbz20 is not null AND crm5 is not NULL AND yybz35 is not null ";
            log.info("获取指定周期内的数据sql:" + strQueryAll);
            rs.execute(strQueryAll);
            String ids = "";
            List<sapMessEntity> gzhsfw_lock = new ArrayList<>();
            sapMessEntity entity_lock;
            //报文请求体
            StringBuffer requestXml;
            requestXml = new StringBuffer();
            //拼接请求体
            requestXml.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:urn='urn:sap-com:document:sap:rfc:functions'>" +
                    "<soapenv:Header/>" + "<soapenv:Body>" + "<urn:ZHRI_075>" + " <RETURN>" +
                    "<!--Zero or more repetitions:-->" +
                    "<item>" +
                    "<TYPE></TYPE>" +
                    "<ID></ID>" +
                    "<NUMBER></NUMBER>" +
                    "<MESSAGE></MESSAGE>" +
                    "<LOG_NO></LOG_NO>" +
                    "<LOG_MSG_NO></LOG_MSG_NO>" +
                    "<MESSAGE_V1></MESSAGE_V1>" +
                    "<MESSAGE_V2></MESSAGE_V2>" +
                    "<MESSAGE_V3></MESSAGE_V3>" +
                    "<MESSAGE_V4></MESSAGE_V4>" +
                    "<PARAMETER></PARAMETER>" +
                    "<ROW></ROW>" +
                    "<FIELD></FIELD>" +
                    "<SYSTEM></SYSTEM>" +
                    "</item>" +
                    "</RETURN>" +
                    "<T_9133>" +
                    "<!--Zero or more repetitions:-->");
            while (rs.next()) {
                ids += rs.getString("id") + ",";
                //获取分公司
                String strFgs = Util.null2String(rs.getString("fgs"));
                log.info("分公司：" + strFgs);
                //获取员工编号
                String strYgbh = Util.null2String(rs.getString("gh"));
                log.info("员工编号：" + strYgbh);
                //获取CRM评分
                String strCRM = Util.null2String(rs.getString("crm5"));
                log.info("CRM评分：" + strCRM);
                //获取零售运营评分
                String strLsyy = Util.null2String(rs.getString("yybz35"));
                log.info("零售运营评分：" + strLsyy);
                //获取服务标准评分
                String strFwbz = Util.null2String(rs.getString("fwbz40"));
                log.info("服务标准评分：" + strFwbz);
                //获取陈列管理
                String strClgl = Util.null2String(rs.getString("clbz20"));
                log.info("陈列管理评分：" + strClgl);
                //获取HR评分
                String strHr = Util.null2String(rs.getString("hr10"));
                log.info("HR评分：" + strHr);
                //总得分
                String strZdf = Util.null2String(rs.getString("zdf"));
                log.info("总得分：" + strZdf);
                //评分日期
                String strPfrq = Util.null2String(rs.getString("khrq"));
                log.info("评分日期：" + strPfrq);
                int year = Integer.parseInt(strPfrq.substring(0, 4));
                int month = Integer.parseInt(strPfrq.substring(5, 7));
                log.info("传至SAP日期：" + dateUtils.getLastDayOfMonth(year, month));
                //姓名
                String strXm = Util.null2String(rs.getString("xm"));
                log.info("员工id:" + strXm);
                //奖金金额
                Double db_jjje = Util.getDoubleValue(rs.getString("jjje"), 0.00);
                log.info("奖金金额：" + db_jjje);
                String strGzfw = sendDataToSapUtils.getGzfwFromUser(strXm);
                log.info("工资核算范围:" + strGzfw);
                String strLockMess = sendDataToSapUtils.judgeLock(log, strGzfw, strPfrq);
                log.info("工资核算范围返回信息:" + strLockMess);
                if (!"".equals(strLockMess)) {
                    strLockMess = "工号为:" + strYgbh + "," + strLockMess + "薪资核算结束后，工资范围解除锁定，流程可以继续提交";
                    log.info(strLockMess);
                    entity_lock = new sapMessEntity();
                    entity_lock.setYgbh(strYgbh);
                    entity_lock.setMessage(strLockMess);
                    entity_lock.setType("E");
                    gzhsfw_lock.add(entity_lock);
                } else {
                    //员工编号
                    requestXml.append(" <item>" + "<PERNR>" + strYgbh + "</PERNR>");
                    //员工编号
                    requestXml.append("<ZCRMPF>" + strCRM + "</ZCRMPF>");
                    //零售运营评分
                    requestXml.append("<ZLSYYPF>" + strLsyy + "</ZLSYYPF>");
                    //服务标准评分
                    requestXml.append("<ZFWBZPF>" + strFwbz + "</ZFWBZPF>");
                    //陈列管理评分
                    requestXml.append("<ZCLGLPF>" + strClgl + "</ZCLGLPF>");
                    //HR评分
                    requestXml.append("<ZHRPF>" + strHr + "</ZHRPF>");
                    //总得分
                    requestXml.append("<ZDF>" + strZdf + "</ZDF>");
                    //传至SAP日期
                    requestXml.append("<ZSP_DATE>" + dateUtils.getLastDayOfMonth(year, month) + "</ZSP_DATE>");
                    //总得分
                    requestXml.append("<ZJE>" + db_jjje + "</ZJE>" + "</item>");
                }
            }
            requestXml.append("</T_9133>" +
                    "</urn:ZHRI_075>" +
                    "</soapenv:Body>" +
                    "</soapenv:Envelope>");
            List<sapMessEntity> list = sendDataToSapUtils.toSapMethod(log, requestXml.toString());
            log.info("消息list集合：" + list);
            String strAllFlag = "";
            String strMessage = "";
            String strGh = "";
            String updateData = "";
            for (sapMessEntity entity : list) {
                log.info("消息类型：" + entity.getType());
                if (entity.getType().equals("allS")) {
                    strAllFlag = "allS";//全部成功
                    strMessage = entity.getMessage();
                } else if (entity.getType().equals("allE")) {
                    strAllFlag = "allE";//全部失败
                    strMessage = entity.getMessage();
                } else {
                    strAllFlag = "E";//部分成功部分失败
                }
            }
            try {
                conn = pool.getConnection();
                statement = conn.createStatement();
                if (ids.length() > 0) {
                    ids = ids.substring(0, ids.length() - 1);
                    log.info("ids=" + ids);
                }
                if (list.size() < 1) {
                    log.info("接口信息解析异常！");
                } else if ("allE".equals(strAllFlag)) {//全部失败
                    log.info("SAP接口传数失败,失败原因：" + strMessage);
                } else if ("allS".equals(strAllFlag)) {//全部成功
                    log.info("传送至SAP全部成功！");
                    updateData = "UPDATE uf_zddpgrjj_qyjl SET " +
                            "tsjg=0,sbyy=''" +
                            " WHERE khzq='" + strKhzq + "' and id in(" + ids + ")";
                    log.info("执行更新sql:" + updateData);
                    statement.addBatch(updateData);
                } else {//部分成功部分失败
                    log.info("接口返回信息：" + list.toString());
                    for (sapMessEntity entity : list) {
                        if (!entity.getType().equals("allS") && !entity.getType().equals("allE")) {
                            strGh = entity.getYgbh();
                            log.info("考核周期：" + strKhzq + ";工号：" + strGh);
                            if (entity.getType().equals("E")) {
                                strMessage = entity.getMessage() + ";";
                                updateData = "UPDATE uf_zddpgrjj_qyjl SET " +
                                        "tsjg=1,sbyy='" + strMessage + "'" +
                                        " WHERE khzq='" + strKhzq + "' and gh='" + strGh + "'";
                                statement.addBatch(updateData);
                            } else {
                                updateData = "UPDATE uf_zddpgrjj_qyjl SET " +
                                        "tsjg=0,sbyy=''" +
                                        " WHERE khzq='" + strKhzq + "' and gh='" + strGh + "'";
                                statement.addBatch(updateData);
                            }
                            log.info("执行更新sql:" + updateData);

                        }
                    }
                }
                if(gzhsfw_lock.size()>0){
                    for (sapMessEntity sapMessEntity : list) {
                        strGh = sapMessEntity.getYgbh();
                        strMessage = sapMessEntity.getMessage() + ";";
                        updateData = "UPDATE uf_zddpgrjj_qyjl SET " +
                                "tsjg=1,sbyy='" + strMessage + "'" +
                                " WHERE khzq='" + strKhzq + "' and gh='" + strGh + "'";
                        statement.addBatch(updateData);
                    }
                }
                Long begin1 = System.currentTimeMillis();
                statement.executeBatch();
                Long end1 = System.currentTimeMillis();
                log.info("批量更新耗时：" + (end1 - begin1) + "(毫秒)");
                conn.close();
                statement.close();
            } catch (Exception ex) {
                log.info("更新sql语句异常：" + ex.toString());
            }
        }
    }

}
